﻿using AutoMapper;
using Customer.API.Applcation.Command.ProcureProductCommand;
using Customer.Domain;
using Customer.Domain.Dto;
using Customer.Infrstructre;
using Customer.Infrstructre.ProcurementManager;
using MediatR;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

namespace Customer.API.Applcation.CommandHandlers.ProcureProductCommandHandler
{
    public class ProcureProductAddCommandHandler : IRequestHandler<ProcureProductAddCommand, int>
    {
        IProcureProductRepository pRep;
        IProcurementRepository mRep;
        EFCoreDBcontext dbContext;
        IMapper _mapper;

        public ProcureProductAddCommandHandler(IProcureProductRepository pRep,IMapper mapper, EFCoreDBcontext dbContext, IProcurementRepository mRep, IMapper _mapper)
        {
            this.pRep = pRep;
            this.dbContext = dbContext;
            this.mRep = mRep;
            this._mapper=_mapper;
    }

        public async Task<int> Handle(ProcureProductAddCommand request, CancellationToken cancellationToken)
        {
            using (var tran = await dbContext.Database.BeginTransactionAsync((System.Data.IsolationLevel.Serializable)))
            {
                
                try
                {
                    var procurement1 = _mapper.Map<Procurement>(request.AddDto);
                    procurement1.ProcureState = 1;

                    // 先处理 procurement1
                    var taskToAdd = await mRep.AddAsync(procurement1);

                    foreach (var item in request.AddDto.ProductDetail)
                    {
                        ProcureProduct detail = new ProcureProduct
                        {
                            IsRecorded = 0,
                            ProcurementCode = procurement1.ProcurementCode,
                            ProductsId = item.ProductsId,
                            ProcureNum = item.ProcureNum,
                            Office_Id = item.Office_Id,
                            User_Id = item.User_Id
                        };
                        await pRep.AddAsync(detail);
                    }

                    // 提交事务
                    await tran.CommitAsync();

                    return 1;  // 返回最终的结果
                }
                catch (Exception)
                {
                    // 回滚事务
                    await tran.RollbackAsync();
                    throw;
                }
            }

        }

    }
}
